package interfaces.hud.spectate;

import gameStates.absGamesStates.gui.AbsHUDState;
import interfaces.GUISource;
import interfaces.hud.pilot.PilotHUD;

import java.util.HashMap;
import java.util.logging.Logger;

import logic.common.player.Player;
import logic.common.team.Team;
import logic.ships.hunter.Hunter;

import org.fenggui.IWidget;

public class SpectateHUD extends PilotHUD {
	
	public static final Logger logger = Logger.getLogger("interfaces.hud.spectate.SpectateHUD");
	
	protected HashMap<SpectateWidget, SpectateListener> spectateMap;
	
	protected int currentPilotIndex;
	protected Player watchedPlayer;
	
	public SpectateHUD(AbsHUDState hudState) {
		super(hudState);
		
		initSpecPlayerContent();
	}
	
	protected void initSpecPlayerContent() {
		int width = hunterStatusHUD.getWidth();
		int height = GUISource.middleFont.getHeight() / 3 * 4;
		SpectatedPlayerContent spc = new SpectatedPlayerContent(width, height);
		spc.setXY(hunterStatusHUD.getX(), hunterStatusHUD.getHeight());
		
		addWidget(spc);
	}
	
	@Override
	public void addWidget(IWidget widget) {
		super.addWidget(widget);
		if(spectateMap == null) spectateMap = new HashMap<SpectateWidget, SpectateListener>();
		
		if(widget instanceof SpectateWidget) {
			SpectateWidget specWidget = (SpectateWidget)widget;
			SpectateListener listener = specWidget.getSpectateListener();
			
			spectateMap.put(specWidget, listener);
		}
	}
	
	@Override
	public void removeWidget(IWidget widget) {
		super.removeWidget(widget);
		
		if(widget instanceof SpectateWidget) spectateMap.remove(widget);
	}
	
	public void changeSpectatedPlayer(boolean next) {
		Player pilot = setIndex(next);
		if(watchedPlayer != pilot) {
			watchedPlayer = pilot;
			Hunter hunter = watchedPlayer.getHunter();
			
			if(hunter != null && !hunter.isDestroyed()) {
				SpectateChangeEvent event = new SpectateChangeEvent(watchedPlayer);
				for(SpectateListener l : spectateMap.values()) {
					l.spectating(event);
				}
				
				ingameState.setCamNode(hunter);
			} else changeSpectatedPlayer(next);
		}
	}
	
	private Player setIndex(boolean next) {
		if(next) currentPilotIndex++;
		else currentPilotIndex--;
		
		Team team = game.getCurrentPlayer().getTeam();
		if(currentPilotIndex < 0) currentPilotIndex = 0;
		else if(currentPilotIndex >= team.getPlayerNumber()) 
			currentPilotIndex = team.getPlayerNumber() - 1;
		
		Player pilot = team.getAllPlayers().get(currentPilotIndex);
		if(pilot == game.getCurrentPlayer()) {
			if(currentPilotIndex == 0) return setIndex(true);
			if(currentPilotIndex == team.getPlayerNumber() - 1) return setIndex(false);
			return setIndex(next);
		}
		return pilot;
	}
	
	public Player getWatchedPlayer() { return watchedPlayer; }
}